import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render,redirect
from .models import etyn,skma,skuj,udbu,lwrt,nhad
from mutagen.mp3 import MP3
import time
from django.core.paginator import Paginator

def index(request):  #首页
    skma_sjrh = skma.objects.all()  #歌曲
    skuj_sjrh = skuj.objects.all()  #歌单
    lwrt_sjrh = lwrt.objects.all()  #轮播图
    
    ujrh = []  #歌单
    paginator = Paginator(skuj_sjrh,5)
    plist = paginator.page_range  #查看有多少页
    for i in plist:
        page1 = paginator.page(i)  #查看哪一页
        ujrh.append(page1)

    marh = []  #歌曲
    p = Paginator(skma_sjrh,9)
    plist1 = p.page_range  #查看有多少页
    for i in plist1:
        page2 = p.page(i)  #查看哪一页
        marh.append(page2)

    data = {
        'marh':marh,
        'ujrh':ujrh,
        'rtrh':lwrt_sjrh
    }
    return render(request,'index.html',data)

def ujqi_rdtf(request):  #音乐排行 
    rvsk = skma.objects.all().order_by("-rtytjgf")[:10]   #热歌榜
    nhad = skma.objects.all().order_by("-nhadjgf")[:10]   #收藏榜
    ussk = skma.objects.all().order_by("-hhwn_time")[:10]  #新歌榜
    data = {
        'rvsk':rvsk,
        'nhad':nhad,
        'ussk':ussk
    }
    return render(request,'ujqi_rdtf.html',data)

def wd(request):  #我的音乐
    try:
        current_user = etyn.objects.get(mtkg=request.session.get('username'))
        nhad_skuj = nhad.objects.filter(mtkg=current_user,skma_id=None)
        nhad_skma = nhad.objects.filter(mtkg=current_user,skuj_id=None)
        return render(request,'wd-code.html',{'nhad_skuj':nhad_skuj,'nhad_skma':nhad_skma})
    except:
        return render(request,'wd.html')
    
def ujqi_nhan(request):   #歌曲收藏
    try:
        id = request.POST['id']
        user = etyn.objects.get(mtkg=request.session.get('username'))
        nhad_skuj = skma.objects.get(skma_id=id) 
        nhad_skuj.nhadjgf+=1
        nhad_skuj.save()
        usfu = nhad()
        usfu.skma_id = nhad_skuj
        usfu.mtkg = user
        usfu.save()
        data = {
            'url':'sm_yung?id='+id
        }
        return JsonResponse(data)
    except:
        data = {
            'url':'logn'
        }
        return JsonResponse(data)

def ujqi_nhan_bcii(request):   #歌曲取消收藏
    try:
        id = request.POST['id']
        user = etyn.objects.get(mtkg=request.session.get('username'))
        nhad_skuj = skma.objects.get(skma_id=id) 
        nhad_skuj.nhadjgf-=1
        nhad_skuj.save()
        usfu = nhad.objects.get(skma_id=nhad_skuj,mtkg=user)
        usfu.delete()
        data = {
            'url':'sm_yung?id='+id
        }
        return JsonResponse(data)
    except:
        data = {
            'url':'logn'
        }
        return JsonResponse(data)
    
def skuj_nhan(request):   #歌单收藏
    try:
        id = request.POST['id']
        user = etyn.objects.get(mtkg=request.session.get('username'))
        nhad_skuj = skuj.objects.get(skuj_id=id) 
        nhad_skuj.nhadjgf+=1
        nhad_skuj.save()
        usfu = nhad()
        usfu.skuj_id = nhad_skuj
        usfu.mtkg = user
        usfu.save()
        data = {
            'url':'uj_yung?id='+id
        }
        return JsonResponse(data)
    except:
        data = {
            'url':'logn'
        }
        return JsonResponse(data)

def skuj_nhan_bcii(request):   #歌曲取消收藏
    try:
        id = request.POST['id']
        user = etyn.objects.get(mtkg=request.session.get('username'))
        nhad_skuj = skuj.objects.get(skuj_id=id) 
        nhad_skuj.nhadjgf-=1
        nhad_skuj.save()
        usfu = nhad.objects.get(skuj_id=nhad_skuj,mtkg=user)
        usfu.delete()
        data = {
            'url':'uj_yung?id='+id
        }
        return JsonResponse(data)
    except:
        data = {
            'url':'logn'
        }
        return JsonResponse(data)

def uj_yung(request):  #歌单页面--用户查看
    try:
        id = request.GET['id']
        ovrn = skuj.objects.get(skuj_id=id)
        ujqi = udbu.objects.filter(skuj_id=ovrn)
        a = False
        try:
            user = etyn.objects.get(mtkg=request.session.get('username'))
            sjrh = nhad.objects.filter(mtkg_id=user,skuj_id=ovrn)[0]
            a = True
            return render(request,'uj_yung.html',{'ovrn':ovrn,'sjrh':sjrh,'a':a,'ujqi':ujqi})
        except:
            return render(request,'uj_yung.html',{'ovrn':ovrn,'a':a,'ujqi':ujqi})
    except:
        return redirect('/')
    
def sm_yung(request):  #歌曲页面--用户查看
    try:
        id = request.GET['id']
        ovrn = skma.objects.get(skma_id=id)
        a = False
        try:
            user = etyn.objects.get(mtkg=request.session.get('username'))
            sjrh = nhad.objects.filter(mtkg_id=user,skma_id=ovrn)[0]
            a = True
            return render(request,'sm_yung.html',{'ovrn':ovrn,'sjrh':sjrh,'a':a})
        except:
            return render(request,'sm_yung.html',{'ovrn':ovrn,'a':a})
    except:
        return redirect('/')

def logn(request):  #登录
    if request.method == "POST":
        userid = request.POST['userid']
        password = request.POST['password']
        sjth = etyn.objects.filter(mtkg=userid,pndc=password).first()
        if sjth:
            request.session["username"] = userid
            print(sjth.scbv)
            if sjth.scbv:
                return redirect('rgck')
            else: 
                return redirect('/')
    return render(request,'logn.html')

def tcdl(request):  #退出
    request.session.flush()
    return redirect('/')

def iymm(request):  #注册
    if request.method == "POST":
        user = request.POST['user']
        try:
            a = etyn.objects.get(mtkg=user)
            return render(request,'iymm.html',{'a':'账号已经存在'})
        except:
            usfu = etyn()
            usfu.mtkg = user   #账号
            usfu.pndc = request.POST['password1']   #密码
            usfu.jntq = request.POST['name']   #昵称
            usfu.mtkg_img = request.FILES.get('iymm_img')   #头像
            usfu.save()
            return redirect('/')
    return render(request,'iymm.html')

def ulpfk(request):  #播放器
    try:
        odkl = request.GET['odkl']
        id = request.GET['id']
        return render(request,'pfk/index.html',{"odkl":odkl,"id":id})
    except:
        return redirect('/')

def wfud(request):  #发送音乐
    try:
        odkl = request.GET['odkl']
        id = request.GET['id']
        if int(odkl)==1:
            sjrh = skma.objects.filter(skma_id=int(id))
            data = []
            for i in sjrh:
                i.rtytjgf+=1
                i.save()
                date = {
                    "name":i.skma_name,
                    "singer":i.skrt,
                    "album":i.kjrh_wvng,
                    "time":i.jfta,
                    "link_url":"media/"+i.skma_ujqi.name,
                    "cover":"media/"+i.skma_img.name,
                    "link_lrc":"media/"+i.skma_txt.name
                }
                data.append(date)
        elif int(odkl)==2:
            sjrh = skuj.objects.get(skuj_id=int(id))
            sjrh.rtytjgf+=1
            sjrh.save()
            ovrn = udbu.objects.filter(skuj_id=sjrh)
            data = []
            for i in ovrn:
                whnt = skma.objects.get(skma_id=i.skma_id.skma_id)
                whnt.rtytjgf+=1
                whnt.save()
                date = {
                    "name":i.skma_id.skma_name,
                    "singer":i.skma_id.skrt,
                    "album":i.skma_id.kjrh_wvng,
                    "time":i.skma_id.jfta,
                    "link_url":"media/"+i.skma_id.skma_ujqi.name,
                    "cover":"media/"+i.skma_id.skma_img.name,
                    "link_lrc":"media/"+i.skma_id.skma_txt.name
                }
                data.append(date)
        else:
            user = etyn.objects.get(mtkg=request.session.get('username'))
            ovrn = nhad.objects.filter(mtkg=user,skuj_id=None)
            data = []
            for i in ovrn:
                whnt = skma.objects.get(skma_id=i.skma_id.skma_id)
                whnt.rtytjgf+=1
                whnt.save()
                date = {
                    "name":i.skma_id.skma_name,
                    "singer":i.skma_id.skrt,
                    "album":i.skma_id.kjrh_wvng,
                    "time":i.skma_id.jfta,
                    "link_url":"media/"+i.skma_id.skma_ujqi.name,
                    "cover":"media/"+i.skma_id.skma_img.name,
                    "link_lrc":"media/"+i.skma_id.skma_txt.name
                }
                data.append(date)
        return JsonResponse({'data':data})
    except:
        return redirect('/')

def huatan(request):  #后台
    if request.method == "POST":
        wkdh = skma()
        wkdh.skma_name = request.POST['title_name']  #歌名
        wkdh.skrt = request.POST['username']   #歌手
        wkdh.vtf_time = request.POST['date']   #发行时间
        wkdh.ygtk = request.POST['ygtk']   #语种
        audio = MP3(request.FILES.get('sk-ma'))
        wkdh.jfta = time.strftime("%M:%S",time.gmtime(audio.info.length))   #时长
        wkdh.iyir = request.POST['iyir']   #流派
        wkdh.kjrh_wvng = request.POST['kjrhwvng']   #唱片公司
        wkdh.skma_img = request.FILES.get('whww_img')  #歌曲图片
        wkdh.skma_ujqi = request.FILES.get('sk-ma') #歌曲音乐
        wkdh.skma_txt = request.FILES.get('sk-yn')  #歌曲歌词
        wkdh.save()
    rnde = skma.objects.all()
    return render(request,'huatan.html',{'rnde':rnde})

def skma_mmbw(request):   #歌曲删除
    if request.method == "POST":
        id = request.POST['skma_id']
        try:
            mmbw = skma.objects.get(skma_id = id)
            mmbw.delete()
            data = {
                "ovtn":"删除成功！"
            }
        except:
            data = {
                "ovtn":"删除失败！"
            }
        return JsonResponse(data)
    
def skma_whnt(request):   #歌曲修改
    if request.method == "POST":
        whnt = skma.objects.get(skma_id = int(request.POST['id']))  #查找哪一个
        whnt.skma_name = request.POST['title_name']  #歌名
        whnt.skrt = request.POST['username']   #歌手
        # whnt.vtf_time = request.POST['date']   #发行时间
        whnt.ygtk = request.POST['ygtk']   #语种
        whnt.iyir = request.POST['iyir']   #流派
        whnt.kjrh_wvng = request.POST['kjrhwvng']   #唱片公司
        if request.FILES.get('whww_img') != None:
            whnt.skma_img = request.FILES.get('whww_img')  #歌曲图片
        if request.FILES.get('sk-ma') != None:
            print(1)
            audio = MP3(request.FILES.get('sk-ma'))
            whnt.jfta = time.strftime("%M:%S",time.gmtime(audio.info.length))   #时长
            whnt.skma_ujqi = request.FILES.get('sk-ma') #歌曲音乐
        if request.FILES.get('sk-yn') != None:
            whnt.skma_txt = request.FILES.get('sk-yn')  #歌曲歌词
        whnt.save()
        return redirect('/rgck')

    sjrh = skma.objects.get(skma_id = request.GET['id'])
    return render(request,'skma_whnt.html',{'sjrh':sjrh})

def skuj_tpgj(request):   #歌单管理
    if request.method == "POST":
        a = skuj()
        a.skuj_name = request.POST['title_name']  #歌单名字
        a.skuj_img = request.FILES.get('whww_img')      #歌单图片
        a.skuj_ttwj = request.POST['tuwj']      #简介
        a.save()
        b = request.POST['select'].split(',')
        for i in b:
            iglk = udbu()
            iglk.skuj_id = a
            iglk.skma_id = skma.objects.get(skma_id = i)
            iglk.save()
        return redirect('/skuj')
    wguk = skuj.objects.all()
    return render(request,'skuj_tpgj.html',{'wguk':wguk})

def wguk_skma(request):   #获取全部歌曲
    data = []
    wguk = skma.objects.all()
    for i in wguk:
        a = {'name':i.skma_name,'value':i.skma_id}
        data.append(a)
    if request.method == "POST":
        id = request.POST['id']
        dv = skuj.objects.get(skuj_id = id)
        ugbuovrn = udbu.objects.filter(skuj_id = dv)
        date=[]
        for i in ugbuovrn:
            date.append(i.skma_id.skma_id)
        print(date)
        date = {'data':data,'date':date}
        return JsonResponse(date)
    date = {'data':data}
    return JsonResponse(date)

def skuj_tuwj(request):   #查看歌单简介
    if request.method == "POST":
        id = request.POST['id']
        data = {
            'data':skuj.objects.get(skuj_id=id).skuj_ttwj
        }
        return JsonResponse(data)

def skuj_mmbw(request):   #歌单删除
    if request.method == "POST":
        id = request.POST['id']
        try:
            mmbw = skuj.objects.get(skuj_id=id)
            mmbw.delete()
            data = {
                "ovtn":"删除成功！"
            }
        except:
            data = {
                "ovtn":"删除失败！"
            }
        return JsonResponse(data)

def skuj_whnt(request):   #歌单修改
    if request.method == "POST":
        a = skuj.objects.get(skuj_id = request.POST['id'])
        a.skuj_name = request.POST['title_name']  #歌单名字
        if request.FILES.get('whww_img') !=None:
            a.skuj_img = request.FILES.get('whww_img')      #歌单图片
        a.skuj_ttwj = request.POST['tuwj']      #简介
        a.save()
        b = request.POST['select'].split(',')   #歌曲歌单关联
        ov_mm = udbu.objects.filter(skuj_id=a)
        for i in ov_mm:    #删除已有关联
            i.delete()
        for i in b:  #加入所有关联
            iglk = udbu()
            iglk.skuj_id = a
            iglk.skma_id = skma.objects.get(skma_id = i)
            iglk.save()
        return redirect('/skuj')
    id = request.GET['id']
    ovrn = skuj.objects.get(skuj_id = id)
    return render(request,'skuj_whnt.html',{'ovrn':ovrn})

def etyn_tpgj(request):    #用户管理
    if request.method == "POST":   #用户删除
        try:
            id = request.POST['id']
            mmbw = etyn.objects.get(mtkg=id)
            mmbw.delete()
            data={
                'data':"删除成功"
            }
        except:
            data={
                'data':"删除失败"
            }
        return JsonResponse(data)
    ovtn = etyn.objects.filter(scbv=False)
    return render(request,'etyn_tpjg.html',{'ovtn':ovtn})

def lwrt_tpgj(request):   #轮播管理
    if request.method == "POST":
        try:
            id = request.POST['id']
            mmdw = lwrt.objects.get(lwrt_id=id)
            mmdw.delete()
            data={
                    'data':"删除成功"
                }
        except:
            data={
                'data':"删除失败"
            }
        return JsonResponse(data)
    lwrt_ovtn = lwrt.objects.all()
    return render(request,'lwrt_tpgj.html',{'lwrt_ovtn':lwrt_ovtn})

def lwrt_usfu(request):   #轮播新增
    if request.method == "POST":
        print(request.POST)
        usfu = lwrt()
        usfu.lwrt_img = request.FILES.get('lwrt_img')
        usfu.skma_id = skma.objects.get(skma_id=request.POST.get('select'))
        usfu.save()
        return redirect('/lwrt')

def lwrt_skma_sjrh(request):  #轮播歌曲查看
    lwrt_sjrh = lwrt.objects.all()
    skma_sjrh = skma.objects.all()
    data = []
    for i in skma_sjrh:
        b = len(lwrt_sjrh)
        for j in lwrt_sjrh:
            if i.skma_id != j.skma_id.skma_id:
                b-=1
        if b==0:
            a = {'name':i.skma_name,'value':i.skma_id}
            data.append(a)
    return JsonResponse({'data':data})

# Create your views here.
